﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SX.Core
{
    /// <summary>
    /// 文件上传
    /// </summary>
    public class FileUploadHelper
    {
        /// <summary>
        /// 上传单文件
        /// </summary>
        /// <param name="file"></param>
        /// <param name="config"></param>
        /// <param name="dirName"></param>
        /// <returns></returns>
        public static async Task<IApiResult<string>> UploadAsync(IFormFile file, UploadConfig config,string dirName="file")
        {
            var result = new ApiResult<string>();
            if (file == null || file.Length < 1)
            {
                return result.NotOk("请上传文件！");
            }
            //比如设置文件存放得位置 
            if (config.RootPath.IsNull())
            {
                config.RootPath = AppContext.BaseDirectory;
            }
            var ext = Path.GetExtension(file.FileName).ToLower();

            //格式限制
            if (!config.Ext.ToLower().Split("|").ToList().Contains(ext))
            {
                return result.NotOk("文件格式不被允许，只能是"+config.Ext);
            }
            //大小限制
            if (file.Length >= config.MaxSize)
            {
                return result.NotOk("文件过大");
            }
            var dateDir = DateTime.Now.ToString("yyyy-MM-dd");
            var uploadPath= Path.Combine(config.RootPath,config.RootDirName,dirName,dateDir );
            uploadPath = uploadPath.Replace("\\", "/");

            //目录不存在创建
            if (!Directory.Exists(uploadPath))
            {
                Directory.CreateDirectory(uploadPath);
            }        
            string filename = DateTime.Now.To_UnixTime()+"_"+file.FileName;
            var filePath = Path.Combine(uploadPath, filename);
            filePath = filePath.Replace("\\", "/");

            var url = $@"/{config.RootDirName}/{dirName}/{dateDir}/{filename}";
            try
            {
                //检查文件名是否重复
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
            }
            catch(Exception ex)
            {
                return result.NotOk(ex.Message);
            }
            return result.Ok(url);
        }

    }
    /// <summary>
    /// 上传配置
    /// </summary>
   public class UploadConfig
    {
        public UploadConfig(string rootPath)
        {
            this.RootPath = rootPath;
        }
        public UploadConfig(FileServer server,string rootPath,string rootDirName, string ext,long maxSize)
        {
            this.Server = server;
            this.RootPath = rootPath;
            this.Ext = ext;
            this.RootDirName = rootDirName;
            this.MaxSize = maxSize;
        }
        /// <summary>
        /// 文件服务器
        /// </summary>
        public FileServer Server { get; set; } = FileServer.Localhost;

        public string RootDirName { get; set; } = "Files";
        /// <summary>
        ///可以是wwwroot和程序根目录
        /// </summary>
        public string RootPath { get; set; }
        /// <summary>
        /// 允许上传得文件类型
        /// </summary>
        public string Ext { get; set; } = ".jpg|.jpeg|.png|.xls|.xlsx|.zip|.ppt|.pptx|.pdf|.rar|.mp3|.gif|.docx|.doc";
        /// <summary>
        /// 默认一个G
        /// </summary>
        public long MaxSize { get; set; } = 1024 * 1024 * 1024;
    }

    /// <summary>
    /// 文件服务器类型
    /// </summary>
    public enum FileServer
    {
        [Description("本地服务器")]
        Localhost = 0,
        [Description("阿里云服务器")]
        AliOss = 1,
        [Description("腾讯云服务器")]
        TxOss = 2,
        [Description("七牛云服务器")]
        QiNiuOss = 3,
    }
}
